//
//  HousekeeperViewController.m
//  JiuLe
//
//  Created by 黄鑫 on 2016/11/9.
//  Copyright © 2016年 Fine. All rights reserved.
//

#import "HousekeeperViewController.h"
#import "MessageViewController.h"
#import "ArticleViewController.h"
#import "HealthReportViewController.h"
#import "OrderViewController.h"
#import "OpinionViewController.h"
#import "PaymentViewController.h"

@interface HousekeeperViewController ()
@property (strong, nonatomic) NSMutableDictionary *dictModel;
@end

@implementation HousekeeperViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"天使管家";
    [self showNavgationWithLeftItemWithTitle:@"首页"];
    _dictModel = [NSMutableDictionary dictionary];
    [self requestPushMessages];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    [self.navigationController setToolbarHidden:NO animated:YES];
    [self initToolbar];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    [self.navigationController setToolbarHidden:YES animated:YES];
}

#pragma mark - 数据请求
- (void)requestPushMessages{
    [SVProgressHUD showWithStatus:@"获取通知" maskType:SVProgressHUDMaskTypeClear];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:[[NSUserDefaults standardUserDefaults] objectForKey:UserDataID] forKey:@"user_id"];
    [[BaseDataRequest alloc] requestPushMessages:dict withBlock:^(id responseObject, NSString *status, NSError *error) {
        [SVProgressHUD dismiss];
        
        if ([status isEqualToString:@"0"]) {
            _dictModel = [responseObject objectForKey:@"result"];
            [self.tableView reloadData];
        }else{
            if (error != nil) {
                TIPSFORVIEW(@"请检测网络设置");
            }else{
                TIPSFORVIEW(@"获取信息失败");
            }
            
        }
    }];
}

- (void)readMessage:(int)type messgaeID:(NSString *)messgaeID{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:[[NSUserDefaults standardUserDefaults] objectForKey:UserDataID] forKey:@"user_id"];
    [dict setObject:[NSNumber numberWithInt:type] forKey:@"type"];
    [dict setObject:messgaeID forKey:@"id"];
    [[BaseDataRequest alloc] readPushMessages:dict withBlock:^(id responseObject, NSString *status, NSError *error) {
    }];
}

#pragma  mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *identifier = @"HousekeeperCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] ;
    }
    UIImageView *image = [cell viewWithTag:1];
    UIImageView *imagePoint = [cell viewWithTag:2];
    imagePoint.image = [UIImage imageNamed:@"earlywarning3"];
    UILabel *labTitle = [cell viewWithTag:3];
    UILabel *labTime = [cell viewWithTag:4];
    UILabel *labContent = [cell viewWithTag:5];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    if(indexPath.section == 0){
        image.image = [UIImage imageNamed:@"earlywarningmassage"];
        labTitle.text = @"预警消息";
        dict = [_dictModel objectForKey:@"warn"];
    }else if (indexPath.section == 1) {
        image.image = [UIImage imageNamed:@"article"];
        labTitle.text = @"文章提醒";
        dict = [_dictModel objectForKey:@"article"];
    }else if (indexPath.section == 2) {
        image.image = [UIImage imageNamed:@"service"];
        labTitle.text = @"服务费到期提醒";
        dict = [_dictModel objectForKey:@"service"];
    }else if (indexPath.section == 3) {
        image.image = [UIImage imageNamed:@"commodity"];
        labTitle.text = @"商品发货通知";
        dict = [_dictModel objectForKey:@"delivery"];
    }else{
        image.image = [UIImage imageNamed:@"health"];
        labTitle.text = @"健康报告提醒";
        dict = [_dictModel objectForKey:@"healthreport"];
    }
    labTime.text = [dict objectForKey:@"add_time"];
    labContent.text = [dict objectForKey:@"remark"];
    if ([[dict objectForKey:@"isread"] isEqualToString:@"no"]) {
        imagePoint.hidden = NO;
    }else{
        imagePoint.hidden = YES;
    }
    return cell;
}

#pragma mark - UITableview Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    int type ;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    if(indexPath.section == 0){
        type = 3;
        dict = [_dictModel objectForKey:@"warn"];
    }else if (indexPath.section == 1) {
        type = 1;
        dict = [_dictModel objectForKey:@"article"];
    }else if (indexPath.section == 2) {
        type = 5;
        dict = [_dictModel objectForKey:@"service"];
    }else if (indexPath.section == 3) {
        type = 2;
        dict = [_dictModel objectForKey:@"delivery"];
    }else{
        type = 4;
        dict = [_dictModel objectForKey:@"healthreport"];
    }
    if ([[dict objectForKey:@"isclick"]isEqualToString:@"no"]) {
        NSLog(@"已读消息");
    }else{
        if(indexPath.section == 0){
            [[_dictModel objectForKey:@"warn"] setObject:@"yes" forKey:@"isread"];
        }else if (indexPath.section == 1) {
             [[_dictModel objectForKey:@"article"]setObject:@"yes" forKey:@"isread"];
        }else if (indexPath.section == 2) {
             [[_dictModel objectForKey:@"service"]setObject:@"yes" forKey:@"isread"];
        }else if (indexPath.section == 3) {
             [[_dictModel objectForKey:@"delivery"]setObject:@"yes" forKey:@"isread"];
        }else{
             [[_dictModel objectForKey:@"healthreport"]setObject:@"yes" forKey:@"isread"];
        }
        [self.tableView reloadData];
        [self readMessage:type messgaeID:[dict objectForKey:@"id"]];
    }

    if(indexPath.section == 0){
        type = 3;
        MessageViewController *message = getStoryOfControllerInstance(@"MessageViewController");
        [self.navigationController pushViewController:message animated:YES];
        dict = [_dictModel objectForKey:@"warn"];
    }else if (indexPath.section == 1) {
        type = 1;
        ArticleViewController *ArticleVC = [[UIStoryboard storyboardWithName:@"ArticleViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"ArticleViewController"];
        [self.navigationController pushViewController:ArticleVC animated:YES];
        dict = [_dictModel objectForKey:@"article"];
    }else if (indexPath.section == 2) {
        type = 5;
        PaymentViewController *userInfo = [[UIStoryboard storyboardWithName:@"PersonalViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"PaymentViewController"];
        [self.navigationController pushViewController:userInfo animated:YES];
        dict = [_dictModel objectForKey:@"service"];
    }else if (indexPath.section == 3) {
        type = 2;
        OrderViewController *userInfo = [[UIStoryboard storyboardWithName:@"PersonalViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"OrderViewController"];
        [self.navigationController pushViewController:userInfo animated:YES];
        dict = [_dictModel objectForKey:@"delivery"];
    }else{
        type = 4;
        HealthReportViewController *healthReport = [[UIStoryboard storyboardWithName:@"HealthReportViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"HealthReportViewController"];
        [self.navigationController pushViewController:healthReport animated:YES];
        dict = [_dictModel objectForKey:@"healthreport"];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 15;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

- (void)dialNumber{
    UIWebView*callWebview =[[UIWebView alloc] init];
    NSURL *telURL =[NSURL URLWithString:@"tel:4009696966"];
    [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
    [self.view addSubview:callWebview];
}

- (void)feedback{
    OpinionViewController *versionVC = [[UIStoryboard storyboardWithName:@"PersonalViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"OpinionViewController"];
    [self.navigationController pushViewController:versionVC animated:YES];
}

- (void)initToolbar{
    UIButton *btnDial = [UIButton buttonWithType:UIButtonTypeCustom];
    btnDial.frame = CGRectMake(0, 0,( SCREEN_WIDTH -60)/2, 40);
    btnDial.backgroundColor = RGB(247,131,3);
    [btnDial setAttributedTitle:[self setBottonTiele:@"拨打电话" withImageName:@"icon_phon"] forState:UIControlStateNormal];
    [btnDial setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btnDial.clipsToBounds=YES; btnDial.layer.cornerRadius=20;
    [btnDial addTarget:self action:@selector(dialNumber) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *btn1=[[UIBarButtonItem alloc] initWithCustomView:btnDial];

    UIButton *btnDial1 = [UIButton buttonWithType:UIButtonTypeCustom];
    btnDial1.frame = CGRectMake(0, 0,( SCREEN_WIDTH -60)/2, 40);
    btnDial1.backgroundColor = RGB(247,131,3);
    [btnDial1 setAttributedTitle:[self setBottonTiele:@"意见反馈" withImageName:@"icon_edit"] forState:UIControlStateNormal];
    [btnDial1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btnDial1.clipsToBounds=YES; btnDial1.layer.cornerRadius=20;
    [btnDial1 addTarget:self action:@selector(feedback) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *btn2=[[UIBarButtonItem alloc] initWithCustomView:btnDial1];
    
    UIBarButtonItem *btn4=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    NSArray *arr1=[[NSArray alloc]initWithObjects:btn4,btn1,btn4,btn2,btn4, nil];
    self.toolbarItems = arr1;
    self.navigationController.toolbar.clipsToBounds = YES;//去黑色线
    [self.navigationController.toolbar setBackgroundColor:RGB(238, 238, 238)];
}

- (NSMutableAttributedString *)setBottonTiele:(NSString *)title withImageName:(NSString *)imageName{
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] init];
    // 创建图片图片附件
    NSTextAttachment *attach = [[NSTextAttachment alloc] init];
    attach.image = [UIImage imageNamed:imageName];
    attach.bounds = CGRectMake(0, -3, 17, 17);
    NSAttributedString *attachString = [NSAttributedString attributedStringWithAttachment:attach];
    [string appendAttributedString:attachString];
    [string appendAttributedString:[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"  %@",title]]];
    [string addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(3, 4)];
    [string addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:17] range:NSMakeRange(3, 4)];
    return string;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
